import React from 'react';

// 简单的 SVG 图标组件，用于测试
type SimpleSvgIconProps = {
  name: string;
  size?: number;
  className?: string;
  style?: React.CSSProperties;
};

// 手动导入图标映射
const iconMap: Record<string, React.FC<React.SVGProps<SVGSVGElement>>> = {};

// 动态导入函数
const loadIcon = async (name: string) => {
  try {
    const module = await import(`@/assets/icon/${name}.svg?react`);
    return module.default;
  } catch (error) {
    console.error(`Failed to load icon: ${name}`, error);
    return null;
  }
};

const SimpleSvgIcon: React.FC<SimpleSvgIconProps> = ({
  name,
  size = 24,
  className = '',
  style = {},
}) => {
  const [IconComponent, setIconComponent] = React.useState<React.FC<
    React.SVGProps<SVGSVGElement>
  > | null>(null);

  React.useEffect(() => {
    // 检查是否已经缓存
    if (iconMap[name]) {
      setIconComponent(() => iconMap[name]);
      return;
    }

    // 动态加载图标
    loadIcon(name).then(Component => {
      if (Component) {
        iconMap[name] = Component;
        setIconComponent(() => Component);
      }
    });
  }, [name]);

  if (!IconComponent) {
    return (
      <div
        style={{
          width: size,
          height: size,
          backgroundColor: '#f0f0f0',
          display: 'inline-block',
          ...style,
        }}
        className={className}
      />
    );
  }

  return <IconComponent width={size} height={size} className={className} style={style} />;
};

export default SimpleSvgIcon;
